package org.eclipse.soc.ide4edu.assignment.editors;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.editor.FormEditor;
import org.eclipse.ui.forms.editor.FormPage;
import org.eclipse.ui.forms.widgets.ScrolledForm;

public class TextPage extends FormPage {

	BufferStore bufferStore;
	StyledText text;
	OpenPage page;

	public TextPage(FormEditor editor, BufferStore buff, OpenPage page) {
		super(editor, "text", "Text");
		this.bufferStore = buff;
		this.page = page;
	}

	@Override
	protected void createFormContent(IManagedForm managedForm) {
		ScrolledForm form = managedForm.getForm();
		GridLayout layout = new GridLayout();
		layout.numColumns = 1;
		form.getBody().setLayout(layout);

		form.setText("Text View");
		layout = new GridLayout();
		layout.numColumns = 2;
		Composite composite = form.getBody();
		composite.setLayout(layout);
		GridData gd = new GridData(GridData.FILL_BOTH);
		text = new StyledText(composite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER
				| SWT.READ_ONLY);
		initText();
		text.setLayoutData(gd);
		gd.horizontalSpan = 2;

		Button edit = new Button(composite, SWT.PUSH);
		edit.setText("Edit");
		edit.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {

				editText();
			}
		});

		Button hide = new Button(composite, SWT.PUSH);
		hide.setText("Hide");
		hide.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				hidePage();
			}
		});

	}

	private void editText() {
		EditorDialog dialog = new EditorDialog(getSite().getShell(),
				bufferStore);
		dialog.open();
	}

	private void hidePage() {
		// todo
	}

	private void initText() {
		text.setText(bufferStore.getText());
		setStyles(text);

	}

	private void setStyles(StyledText edit) {

		try {
			StyleRange[] styles = bufferStore.getStyleRanges(getSite()
					.getShell().getDisplay());
			edit.setStyleRanges(styles);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
